# 视图  Create your views here.
from django.shortcuts import render, redirect, HttpResponse
from .models import UserInfo, Department


# index page
def home(request):
    return render(request, "app15/home.html")


# index page
def index(request):
    return HttpResponse("欢迎使用")


# tpl page
def tpl(request):
    # 字符串
    name = "模板语法学习"
    # 列表（元组）
    roles = ["pengbm", "luott"]  # (1,2)
    # 字典
    dict = {"id": 1, "name": "bingm", "phone": "157****1471", "age": 28}

    # 列表，嵌套字典
    queryset = [
        {"id": 1, "name": "bingm", "phone": "157****1471", "age": 28},
        {"id": 2, "name": "luott", "phone": "157****4120", "age": 28},
    ]
    return render(
        request,
        "app15/tpl.html",
        {"name": name, "roles": roles, "dict": dict, "queryset": queryset},
    )


# news page
def api(request):
    # 1.定义一些新闻（字典或者列表） 或 去数据库  网络请求去联通新闻
    # 向地址：http://www.chinaunicom.com.cn/api/article/NewsByIndex/2/2021/11/news 发送请求
    # 第三方模块：requests  (pip install requests)
    import requests

    res = requests.get("http://124.223.20.228:8080/api/data").json()

    # # 返回网页
    return render(request, "app15/news.html", {"news_list": res})
    # # 返回 API json
    # return JsonResponse(res, safe=False)


# something page
def something(request):
    # request是一个对象，封装了用户发送过来的所有请求相关数据

    # 1.获取请求方式 GET/POST
    print(request.method)

    # 2.在URL上传递值 something/?id=123&name=bingm
    print(request.GET)
    # return HttpResponse("come back")
    return render(request, "app15/something.html", {"title": "come"})


# Login page
def login(request):
    # 判断请求类型：POST/GET
    if request.method == "GET":
        return render(request, "app15/login.html")
    else:
        # 获取用户提交的数据
        username = request.POST.get("user")
        password = request.POST.get("pwd")
        if username == "" and password == "":
            return render(request, "app15/login.html", {"error": "请输入账号密码"})
        elif username == "":
            return render(request, "app15/login.html", {"error": "请输入账号"})
        elif password == "":
            return render(request, "app15/login.html", {"error": "请输入密码"})
        elif username == "root" and password == "123":
            return redirect("/index/")
        else:
            return render(request, "app15/login.html", {"error": "用户名或密码错误"})


# 测试 orm 增删查改
def orm(request):

    # 1、添加数据
    # Department.objects.create(title='销售部')
    # Department.objects.create(title='IT部')
    # Department.objects.create(title='运营部')
    # UserInfo.objects.create(name='pengbm',password='123',age=28)
    # UserInfo.objects.create(name='luott',password='123',age=28)

    # 2、删除数据
    # 按 id 号删除
    # Department.objects.filter(id=3).delete()
    # 全部删除
    # Department.objects.all().delete()

    # 3、获取数据
    # data_list = UserInfo.objects.all()
    # for obj in data_list:
    #     print(obj.id,obj.name,obj.password,obj.age)

    # 取第一个
    # data_list = UserInfo.objects.filter(id=1).first()
    # print(data_list.id,data_list.name,data_list.password,data_list.age)

    # 4、更新
    # UserInfo.objects.all().update(age=27)
    # UserInfo.objects.filter(id=1).update(age=26)

    return HttpResponse("success")


# 用户信息
def user_info(request):
    # 获取数据库中用户信息
    if request.method == "GET":
        nid = request.GET.get("nid")
        if nid:
            UserInfo.objects.filter(id=nid).delete()

        info_list = UserInfo.objects.all()
        return render(request, "app15/user_info.html", {"info_list": info_list})

    elif request.method == "POST":
        # 添加用户
        # 获取用户提交的数据
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        age = request.POST.get("age")
        # 添加到数据库
        # UserInfo.objects.all().delete()
        UserInfo.objects.create(name=user, password=pwd, age=age)
        # return redirect('http://127.0.0.1:8000/user/info/')
        return redirect("/user/info/")


# # 添加用户
# def user_add(request):
#     if request.method == "GET":
#         return render(request,'app15/user_add.html')

#     # 获取用户提交的数据
#     user = request.POST.get('user')
#     pwd = request.POST.get('pwd')
#     age = request.POST.get('age')
#     # 添加到数据库
#     # UserInfo.objects.all().delete()
#     UserInfo.objects.create(name=user,password=pwd,age=age)
#     # return redirect('http://127.0.0.1:8000/user/info/')
#     return redirect('/user/info/')


# # 输出用户
# def user_del(request):
#     nid = request.GET.get('nid')
#     UserInfo.objects.filter(id=nid).delete()
#     return redirect('/user/info/')
